package org.walkerljl.config;

import java.util.ArrayList;
import java.util.List;

import org.walkerljl.config.abstracts.AbstractConfigurator;
import org.walkerljl.log.Logger;
import org.walkerljl.log.LoggerFactory;

/**
 * 配置器工厂类,可通过多次调用register方法注册多个Configurator实例<br>
 * <li>如存在多个配置器，获取配置的顺序以先注册的顺序为准 
 * @author lijunlin
 */
public class ConfiguratorFactory extends AbstractConfigurator {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ConfiguratorFactory.class);
	
	/** 配置器列表*/
	private List<Configurator> configurators = new ArrayList<Configurator>();
		
	public static ConfiguratorFactory getInstance() {
		return ConfiguratorFactoryHolder.instance;
	}

	/**
	 * 注册配置器
	 * @param configurator
	 */
	public void register(Configurator configurator) {
		if (configurator != null) {
			configurators.add(configurator);
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug(String.format("注册配置器:%s", configurator.getClass()));
			}
		}
	}
	
	@Override
	public Object getProperty(String key) {
		for (Configurator configurator : configurators) {
			Object value = configurator.getProperty(key);
			if (value != null) {
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug(String.format("从配置器:%s中获取配置, Key:%s, Value:%s", 
							configurator.getClass(), key, (value == null ? "NULL" : value.toString())));
				}
				return value; 
			}
		}
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(String.format("无效的配置Key:%s, 使用默认值", key));
		}
		return null;
	}
	
	/**
	 * 
	 * ConfiguratorFactoryHolder
	 *
	 * @author lijunlin
	 */
	private static class ConfiguratorFactoryHolder {
		private static ConfiguratorFactory instance = new ConfiguratorFactory();
	}
}